<script setup>
import { User, Lock } from '@element-plus/icons-vue'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

//调用后台接口,完成发送短信验证码
import { sendMsgApi, userLoginApi, backendLoginApi } from '@/api/login.js'

// 路由
const router = useRouter()

//控制注册与登录表单的显示， 默认显示注册
const isRegister = ref(false)

//定义用户登录数据模型
const userDataRef = ref(null)
const userData = ref({
    phone: '',
    code: ''
})
//定义表单校验规则
var reg = /^1[3456789]\d{9}$/;
const userDataRules = {
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: reg, message: '手机号码格式不正确', trigger: 'blur' }
    ],
    code: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { min: 4, max: 6, message: '长度4~6位非空字符', trigger: 'blur' }
    ],
}
//用户登录短信验证码
const sendMsg = async () => {
    // 校验表单数据是否合规;
    if (!reg.test(userData.value.phone)) {
        ElMessage.error('手机号码格式不正确')
        return;
    } else {
        // userData,如果要获取值,需要.value
        let result = await sendMsgApi({ phone: userData.value.phone });
        if (result.code === 1) {
            ElMessage.success(result.data ? result.data : '发送成功');
            return;
        } else {
            ElMessage.error(result.msg ? result.msg : '发送失败')
            return;
        };
    }
}
// 用户登录方法
const userLogin = async () => {
    if (!submitForm(userDataRef)) {
        //调用接口,完成登录
        let result = await userLoginApi(userData.value);
        if (result.code === 1) {
            ElMessage.success('登录成功');
            const name = result.data.name;
            window.localStorage.setItem('username', name);
            router.push('/user');
            return;
        } else {
            ElMessage.error(result.msg ? result.msg : '登录失败');
            return;
        }
    } else {
        return;
    }
    //把得到的token存储到pinia中
    //    tokenStore.setToken(result.data);
    //跳转到首页 路由完成跳转
    //    router.push('/');
}
//定义后台登录数据模型
const backendDataRef = ref(null)
const backendData = ref({
    username: '',
    password: ''
})
//定义后台表单校验规则
const backendDataRules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 0, max: 16, message: '长度为5~16位非空字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 0, max: 16, message: '长度为5~16位非空字符', trigger: 'blur' }
    ],
}
// 用户登录方法
const backendLogin = async () => {
    if (!submitForm(backendDataRef)) {
        //调用接口,完成登录
        let result = await backendLoginApi(backendData.value);
        if (result.code === 1) {
            ElMessage.success('登录成功');
            const name = result.data.name;
            window.localStorage.setItem('name', name);
            router.push({
                path: '/backend',
                query: {
                    name: name
                }
            });
            return;
        } else {
            ElMessage.error(result.msg ? result.msg : '登录失败');
            return;
        }
    } else {
        return;
    }
}
//登录通用表单校验方法
const submitForm = (fromEL) => {
    fromEL.value.validate((valid) => {
        if (valid) {
            ElMessage.success("校验通过");
            return true;
        } else {
            ElMessage.error("校验不通过")
            return false;
        }
    })
}
</script>

<template>
    <el-row class="login-page">
        <el-col :xs="0" :sm="12" :md="12" :lg="12" :xl="12" class="bg"></el-col>
        <el-col :xs="22" :sm="10" :md="10" :lg="10" :xl="10" :offset="1" class="form">
            <!-- 后台表单 -->
            <el-form ref="backendDataRef" size="large" autocomplete="off" v-if="isRegister" :model="backendData"
                :rules="backendDataRules">
                <el-form-item>
                    <h1>后台登录</h1>
                </el-form-item>
                <el-form-item prop="username">
                    <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="backendData.username"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码"
                        v-model="backendData.password"></el-input>
                </el-form-item>
                <!-- 后台登录按钮 -->
                <el-form-item>
                    <el-button class="button" type="primary" auto-insert-space @click="backendLogin">
                        后台登录
                    </el-button>
                </el-form-item>
                <el-form-item class="flex">
                    <el-link type="info" :underline="false" @click="isRegister = false">
                        ← 返回
                    </el-link>
                </el-form-item>
            </el-form>
            <!-- 用户登录表单 -->
            <el-form ref="userDataRef" size="large" autocomplete="off" v-else :model="userData" :rules="userDataRules">
                <el-form-item>
                    <h1>餐掌柜订餐用户登录</h1>
                </el-form-item>
                <el-form-item prop="phone">
                    <el-input :prefix-icon="User" placeholder="请输入手机号" v-model="userData.phone"></el-input>
                </el-form-item>
                <el-form-item prop="code">
                    <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入验证码"
                        v-model="userData.code"></el-input>
                </el-form-item>
                <el-form-item class="flex">
                    <div class="flex">
                        <el-link type="info" :underline="false" @click="isRegister = true">
                            后台登录 →
                        </el-link>
                        <el-link type="primary" :underline="false" @click="sendMsg">发送验证码</el-link>
                    </div>
                </el-form-item>
                <el-text class="mx-1" type="info" size="small">未注册用户将为您自动注册!!!</el-text>
                <!-- 登录按钮 -->
                <el-form-item>
                    <el-button class="button" type="primary" auto-insert-space @click="userLogin">登录</el-button>
                </el-form-item>
            </el-form>
        </el-col>
    </el-row>
</template>

<style lang="scss" scoped>
/* 样式 */
.login-page {
    height: 100vh;
    background-color: #fff;

    .bg {
        background: url('@/assets/logo2.png') no-repeat 60% center / 240px auto,
            url('@/assets/login_bg.jpg') no-repeat center / cover;
        border-radius: 0 20px 20px 0;
    }

    .form {
        display: flex;
        flex-direction: column;
        justify-content: center;
        user-select: none;

        .title {
            margin: 0 auto;
        }

        .button {
            width: 100%;
        }

        .flex {
            width: 100%;
            display: flex;
            justify-content: space-between;
        }
    }
}
</style>